package cn.kgc.controller;

import cn.kgc.pojo.AppVersion;
import cn.kgc.pojo.BackendAppInfo;
import cn.kgc.service.Fc_VersionService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;


/**
 * @program:appinosystem
 * @description:
 * @author:冯聪聪
 * @create:2022-01-04 10:27
 */


@RequestMapping("/version")
@Controller
public class Fc_VersionController {

    //获得日志类对象
    Logger logger = Logger.getLogger(Fc_VersionController.class);

    //装配Service属性
    @Resource
    private Fc_VersionService service;

    /**
     * 查询版本页面
     *
     */
    @RequestMapping("/sel")
    public String sel(HttpSession session) {


        //调用查询方法
        List<AppVersion> list = service.selAllVersion(58l);


        session.setAttribute("appVersionList",list);

        return "developer/appversionadd";
    }



    /**
     * 进入添加版本信息界面
     */
    @RequestMapping("/add/{id}")
    public String toAdd(HttpSession session,@PathVariable Integer id) {
        //调用查询方法
        List<AppVersion> list = service.selAllVersion((long)id);
        session.setAttribute("appVersionList",list);
        return "developer/appversionadd";
    }


    /**
     * 进行添加操作
     */
    @RequestMapping("/doAdd")
    public String addVersion(@ModelAttribute AppVersion version, HttpSession session,
                             HttpServletRequest request,
                             @RequestParam(value = "a_downloadLink",required = false) MultipartFile attach){
        System.out.println("获取文件之前"+version.toString()+"\n");

        //保存到数据库的图片路径
        String apkPath = null;
        //新文件名
        String fileName = null;
        //原文件路径
        String path = null;



        //如果文件不为空
        if (!attach.isEmpty()) {
            //获得文件源路径
            path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "upload");
            logger.info("uploadFile path ============== > " + path);

            //获得原文件名
            String oldFileName = attach.getOriginalFilename();
            logger.info("uploadFile oldFileName ============== > " + oldFileName);

            //获得原文件后缀
            String prefix = FilenameUtils.getExtension(oldFileName);
            logger.debug("uploadFile prefix============> " + prefix);

            //设置文件大小5000k,就是5mb
            int filesize = 5000000;
            logger.debug("uploadFile size============> " + attach.getSize());


            //如果源文件大小超过设定值
            if (attach.getSize() > filesize) {
                //进行文件过大提示
                request.setAttribute("uploadFileError", " * 上传大小不得超过 5mb");
                //返回添加页面
                return "developer/appversionadd";

                //如果文件格式(忽略大小写的后缀)是apk格式
            } else if (prefix.equalsIgnoreCase("apk")) {
                //给文件重命名为       当前系统的毫秒数+四位随机数 + .apk后缀
                fileName = System.currentTimeMillis() + RandomUtils.nextInt() + ".apk";
                logger.debug("new fileName======== " + attach.getName());

                File targetFile = new File(path, fileName);
                //如果文件不存在,就生成此文件
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                //保存
                logger.debug("---------------fileName=" + fileName);

                try {
                    //保存文件
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError", " * 上传失败！");
                    return "developer/appversionadd";
                }
                apkPath = path + File.separator + fileName;
            } else {
                request.setAttribute("uploadFileError", " * 上传图片格式不正确");
                return "developer/appversionadd";
            }
        }

        //获得源文件路径(下载地址)  新文件路径  新文件名 赋值给对象的对应属性
        version.setApkLocPath(apkPath);
        version.setApkFileName(fileName);
        version.setDownloadLink(path);

        System.out.println("获取文件后"+version.toString()+"\n");
        //调用业务层添加方法,添加版本信息
        service.addVersion(version);
        //跳转到查询版本页面
        return "developer/appinfolist";
    }



    /**
     * 点击版本修改时，携带当前的版本信息跳转修改版本页面
     */
    @RequestMapping("/toupd/{id}")
    public String toUpd(Model model,HttpSession session,@PathVariable Integer id) {//@PathVariable Integer id,
        //根据id查询单条版本信息
        AppVersion version = service.selOneVersion(id);
        //存入model供前台页面调取其属性值
        model.addAttribute("appVersion", version);

        //调用查询方法
        List<AppVersion> list = service.selAllVersion((long)id);
        logger.debug("开始测试………………");
        for (AppVersion ver : list) {
            logger.debug(ver);
        }

        session.setAttribute("appVersionList",list);
        //携带数据转发到修改页面
        return "developer/appversionmodify";
    }


    /**
     *修改页面的表单提交
     */
    @PostMapping("/upd")
    public String updVersion(@ModelAttribute AppVersion version, HttpSession session,
                             HttpServletRequest request,
                             @RequestParam(value = "a_downloadLink", required = false) MultipartFile attach) {
        //保存到数据库的图片路径
        String apkPath = null;
        //新文件名
        String fileName = null;
        //原文件路径
        String path = null;
        //将文件大小提出来
        double apkSize =0.0;

        //如果文件不为空
        if (!attach.isEmpty()) {
            //获得文件源路径
            path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "upload");
            logger.info("uploadFile path ============== > " + path);

            //获得原文件名
            String oldFileName = attach.getOriginalFilename();
            logger.info("uploadFile oldFileName ============== > " + oldFileName);

            //获得原文件后缀
            String prefix = FilenameUtils.getExtension(oldFileName);
            logger.debug("uploadFile prefix============> " + prefix);

            //设置文件大小5000k,就是5mb
            int filesize = 5000000;
            logger.debug("uploadFile size============> " + attach.getSize());

            apkSize = (double)attach.getSize();
            //如果源文件大小超过设定值
            if (attach.getSize() > filesize) {
                //进行文件过大提示
                request.setAttribute("uploadFileError", " * 上传大小不得超过 5mb");
                //返回添加页面
                return "developer/appversionmodify";

                //如果文件格式(忽略大小写的后缀)是apk格式
            } else if (prefix.equalsIgnoreCase("apk")) {
                //给文件重命名为       当前系统的毫秒数+四位随机数 + .apk后缀
                fileName = System.currentTimeMillis() + RandomUtils.nextInt() + ".apk";
                logger.debug("new fileName======== " + attach.getName());

                File targetFile = new File(path, fileName);
                //如果文件不存在,就生成此文件
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                //保存
                logger.debug("---------------fileName=" + fileName);

                try {
                    //保存文件
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError", " * 上传失败！");
                    return "developer/appversionmodify";
                }
                apkPath = path + File.separator + fileName;
            } else {
                request.setAttribute("uploadFileError", " * 上传图片格式不正确");
                return "developer/appversionmodify";
            }
        }

        //获得源文件路径(下载地址)  新文件路径  新文件名 赋值给对象的对应属性
        version.setVersionSize(apkSize);
        version.setApkLocPath(apkPath);
        version.setApkFileName(fileName);
        version.setDownloadLink(path);

        //调用业务层修改方法,添加版本信息
        service.updVersion(version);

        //跳转到查询版本页面
        return "redirect:/wxw/toapp";
    }



    @RequestMapping("/infoview/{id}")
    public String infoview(HttpSession session,@PathVariable Integer id){
        //调用查询方法
        List<AppVersion> list = service.selAllVersion((long)id);
        session.setAttribute("appVersionList",list);


        BackendAppInfo appInfo = service.selAppInfoById(id);
        session.setAttribute("appInfo",appInfo);


        return "developer/appinfoview";
    }

    }

